package com.qianda.qdminiapp.common.rabbitmq;

import com.alibaba.fastjson.JSONObject;
import com.qianda.qdminiapp.common.exception.ExceptionCode;
import com.qianda.qdminiapp.common.exception.SimpleException;
import com.qianda.qdminiapp.common.future.CommandFuture;
import com.qianda.qdminiapp.common.future.CommandFutureManager;
import com.qianda.qdminiapp.common.future.SendData;
import com.qianda.qdminiapp.config.RabbitConfig;
import com.qianda.qdminiapp.dao.device.DeviceDao;
import com.qianda.qdminiapp.dao.device.QqdDeviceDao;
import com.qianda.qdminiapp.domain.model.device.Device;
import com.qianda.qdminiapp.domain.model.device.QqdDevice;
import com.qianda.qdminiapp.domain.model.order.Order;
import com.qianda.qdminiapp.domain.model.order.QqdOrderTowel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @ClassName MsgProducer
 * @Author cw
 * @Date 2019/8/8 10:47
 * @Version 1.0
 */
@Component
public class MsgProducer implements RabbitTemplate.ConfirmCallback{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private CommandFutureManager futureManager;

    @Autowired
    private QqdDeviceDao deviceDao;

    //由于rabbitTemplate的scope属性设置为ConfigurableBeanFactory.SCOPE_PROTOTYPE，所以不能自动注入
    private RabbitTemplate rabbitTemplate;

    /**
     * 构造方法注入rabbitTemplate
     */
    @Autowired
    public MsgProducer(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
        rabbitTemplate.setConfirmCallback(this); //rabbitTemplate如果为单例的话，那回调就是最后设置的内容
    }

    public void sendMsg(String content) {
        Map<String,Object> contentMap = (Map<String, Object>) JSONObject.parse(content);
        Integer protocolsV = 1;//协议版本
        protocolsV = (Integer) contentMap.get("protocolsV");
        CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());

        //版本一协议放队列A，版本二协议放队列B
       if(protocolsV == 0){
           logger.info("开始向mq里发放消息");
           rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_C, RabbitConfig.ROUTINGKEY_C, content, correlationId);
       }else{
           System.out.println("发送消息:"+content);
           rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_B, RabbitConfig.ROUTINGKEY_B, content, correlationId);
       }

    }

    /**
     * 回调
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        logger.info(" 回调id:" + correlationData);
        if (ack) {
            logger.info("消息成功消费");
        } else {
            logger.info("消息消费失败:" + cause);
        }
    }

    public CommandFuture send(SendData data,
                              String futureId,
                              long ttl) {

        String channel = data.getChannel();
        int command = data.getCommand();

        CommandFuture future = new CommandFuture(channel, command);
        if (!futureManager.add(futureId, future, ttl)) {
            // 此处返回添加失败的原因目前为已经发送过该指令了
            throw new RuntimeException("The future id " + futureId + " exists");
        }

        String msg = new JSONObject(data).toJSONString();
        sendMsg(msg);

        return future;
    }

    public Object sendCommand(QqdOrderTowel order, Integer command) {
        QqdDevice device = deviceDao.selectById(order.getOrderDeviceId());
        SendData data = new SendData();
        data.put("protocolsV", device.getDeviceProtocolsVersion());
        data.put("orderId", order.getOrderNo());
        data.put("towelLength",order.getOrderDeviceLength());
        data.put("count",order.getOrderCount());
        data.put("imei",device.getImei());
        data.put("command",command);
        String msg = new JSONObject(data).toJSONString();
        sendMsg(msg);
     //   send(data, device.getDeviceCcid(), 10l);

        return  null;
    }
}
